/**
 * 漆水河 脚手架基础公开课
 * 2022/8/13 --- 2022/12/13
 * 有疑问可加QQ群: 809126489，后续会持续输出与大家一起成长
 */
package com.qishuihe.basedomain.infrastructure.handler;

import com.baomidou.mybatisplus.extension.parser.JsqlParserSupport;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.qishuihe.basedomain.infrastructure.vo.LoginUserVO;
import com.qishuihe.basedomain.infrastructure.handler.method.MySqlMethod;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Date;


@Slf4j
public class MyLogicDeleInterceptor  extends JsqlParserSupport implements InnerInterceptor {

    private String UPDATE_BY="updateBy";
    private String UPDATE_DATE="updateDate";
    @Override
    public void beforeUpdate(Executor executor, MappedStatement ms, Object parameter)  {

        String id =  ms.getId();
        if(id.endsWith(MySqlMethod.LOGIC_DELETE_BATCH_BY_IDS.getMethod())||
                id.endsWith(MySqlMethod.LOGIC_DELETE_BY_MAP.getMethod())||
                id.endsWith(MySqlMethod.LOGIC_DELETE.getMethod())){
            MapperMethod.ParamMap paramMap = null;
            paramMap = (MapperMethod.ParamMap) parameter;
            paramMap.put(UPDATE_BY,123456);
            paramMap.put(UPDATE_DATE,new Date());
            parameter =initLogicDeletInfo(paramMap);
            log.debug("add updateDate, updateBy");
        }
    }

    private MapperMethod.ParamMap initLogicDeletInfo(MapperMethod.ParamMap paramMap){
        paramMap.put(UPDATE_DATE,new Date());
        paramMap.put(UPDATE_BY,1);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(null!=authentication) {
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
            LoginUserVO loginUserDTO = (LoginUserVO) usernamePasswordAuthenticationToken.getPrincipal();
            paramMap.put(UPDATE_BY,loginUserDTO.getUsername());
        }
        return paramMap;
    }
}
